package controller

import (
	"smc-admin/models"
	"smc-admin/response"
	"smc-admin/utils"
	"strconv"

	"github.com/gin-gonic/gin"
)

type Img struct {
	Name     string `form:"name" binding:"required"`
	TypesId  int    `form:"typesId" binding:"required"`
	FileList string `form:"fileList"`
}

type ImgById struct {
	ID int `form:"id" binding:"required"`
	Img
}

// @Tags         图片管理
// @Summary      图片更新
// @Param        img  body	Img  true  "图片"
// @Success      200       {object}  response.Body
// @Router       /img/update [PUT]
func UpdateImg(ctx *gin.Context) {
	var img ImgById
	err := ctx.ShouldBindJSON(&img)
	if err != nil {
		panic(err.Error())
	}

	//更新
	i := models.Img{
		BaseModel: models.BaseModel{
			ID: img.ID,
		},
	}
	updateErr := i.Update(map[string]interface{}{
		"name":      img.Name,
		"types_id":  img.TypesId,
		"file_list": img.FileList,
	})
	if updateErr != nil {
		panic(updateErr.Error())
	}
	response.Success(ctx)
}

// @Tags         图片管理
// @Summary      图片添加
// @Param        img  body	Img  true  "图片"
// @Success      200       {object}  response.Body
// @Router       /img/add [POST]
func AddImg(ctx *gin.Context) {
	var img Img
	error := ctx.ShouldBindJSON(&img)
	if error != nil {
		panic(error.Error())
	}

	i := models.Img{
		FileList: img.FileList,
		TypesID:  img.TypesId,
		Name:     img.Name,
	}
	e := i.Add()
	if e != nil {
		panic(e.Error())
	}

	response.Success(ctx)
}

// @Tags         图片管理
// @Summary      图片分页查询
// @Param        id	query	int  false  "id"
// @Param        name	query	string  false  "名称"
// @Param        typesId	query	int  false  "类型id"
// @Param        pageSize	query	string  false  "分页大小"
// @Param        pageNum	query	string  false  "分页数量"
// @Success      200       {object}  response.Body
// @Router       /img/findByPage [get]
func FindImgByPage(ctx *gin.Context) {
	name := ctx.Query("name")
	id, _ := strconv.Atoi(ctx.Query("id"))
	typesId, _ := strconv.Atoi(ctx.Query("typesId"))

	i := models.Img{
		BaseModel: models.BaseModel{
			ID: id,
		},
		Name:    name,
		TypesID: typesId,
	}
	data, total, err := i.FindByPage(utils.PageQuery(ctx))
	if err != nil {
		panic(err.Error())
	}
	response.Success(ctx, response.Body{
		Data: map[string]interface{}{
			"data":  data,
			"total": total,
		},
	})
}

// @Tags         图片管理
// @Summary      图片删除
// @Param        id	query	string  false  "图片id"
// @Success      200       {object}  response.Body
// @Router       /img/delete [DELETE]
func DeleteImg(ctx *gin.Context) {
	deleteId, _ := strconv.Atoi(ctx.Query("id"))

	i := models.Img{
		BaseModel: models.BaseModel{
			ID: deleteId,
		},
	}
	err := i.Delete()
	if err != nil {
		panic(err)
	}
	response.Success(ctx)
}
